package com.xiaoxiang.text.util;

import orestes.bloomfilter.CountingBloomFilter;
import orestes.bloomfilter.FilterBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 布隆过滤器
 * @author: haha
 * @date: 2022/4/24 17:38
 */
@Component
public class BloomFilter {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    /**
     * 期望的元素数量
     */
    private static final int EXCEPT_NUM = 10000;

    /**
     * 错误率
     */
    private static final double ERROR_RATE = 0.01;

    public void add(String name, String value) {
        CountingBloomFilter<String> cbfr = new FilterBuilder(EXCEPT_NUM, ERROR_RATE)
                .name(name)
                .redisBacked(true)
                .redisHost(host)
                .redisPort(port)
                .buildCountingBloomFilter();
        cbfr.add(value);
    }

    public boolean contains(String name, String value) {
        CountingBloomFilter<String> cbfr = new FilterBuilder(EXCEPT_NUM, ERROR_RATE)
                .name(name)
                .redisBacked(true)
                .redisHost(host)
                .redisPort(port)
                .buildCountingBloomFilter();
        return cbfr.contains(value);
    }

    public void remove(String name, String value) {
        CountingBloomFilter<String> cbfr = new FilterBuilder(EXCEPT_NUM, ERROR_RATE)
                .name(name)
                .redisBacked(true)
                .redisHost(host)
                .redisPort(port)
                .buildCountingBloomFilter();
        cbfr.remove(value);
    }
}
